from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import F
from django.urls import reverse
from django.utils import timezone

from .models import Question, Choice
from .forms import VoteForm


def index(request):
    now = timezone.now()
    qs = Question.objects.filter(pub_date__lt=now)[:5]
    return render(request, 'polls/index.html', context={'latest_questions': qs})


def detail(request, pk):
    now = timezone.now()
    q = get_object_or_404(Question, pk=pk, pub_date__lt=now)
    return render(request, 'polls/detail.html', context={'question': q})


def results(request, pk):
    q = get_object_or_404(Question, pk=pk)
    return render(request, 'polls/results.html', context={'question': q})


def vote(request, pk):
    if request.method == 'POST':
        form_data = {'question': pk}
        form_data.update(request.POST)
        form = VoteForm(form_data)
        if form.is_valid():
            cpk = form.cleaned_data['choice']
            Choice.objects.filter(pk=cpk).update(votes=F('votes')+1)
            results_url = reverse('polls:results', kwargs={'pk': pk})
            return HttpResponseRedirect(redirect_to=results_url)
    back_url = request.META.get('HTTP_REFERER')
    if back_url:
        return HttpResponseRedirect(redirect_to=back_url)
    else:
        return HttpResponse('Invalid operation', status=400)
